#include "common.h"

#include <QApplication>
#include <QDesktopWidget>
#include <QDir>
#include <QFile>
#include <QJsonObject>
#include <QJsonParseError>
#include <QMap>
#include <QMessageBox>
#include <QWidget>

QString Common::m_typePath = FILETYPEDIR;
QStringList Common::m_typeList = QStringList();
QNetworkAccessManager* Common::m_netManager = new QNetworkAccessManager;

Common::Common(QObject *parent) : QObject(parent)
{

}

//在窗口屏幕中心显示
void Common::moveToCenter(QWidget *tmp)
{
    //显示窗口
    tmp->show();
    QDesktopWidget* desktop = QApplication::desktop();
    tmp->move((desktop->width() - tmp->width()) / 2, (desktop->height() - tmp->height()) / 2);
}

void Common::writeWebInfo(QString ip, QString port, QString path)
{
    QMap<QString, QVariant> Web_server;
    Web_server.insert("ip", ip);
    Web_server.insert("port", port);

    QMap<QString, QVariant> type_path;
    type_path.insert("path", m_typePath);

    QString user = getCfgValue("login", "user");
    QString pwd = getCfgValue("login", "pwd");
    QString remember = getCfgValue("login", "remember");

    QMap<QString, QVariant> login;
    login.insert("user", user);
    login.insert("pwd", pwd);
    login.insert("remember", remember);

    QMap<QString, QVariant> json;
    json.insert("web_server", Web_server);
    json.insert("type_path", type_path);
    json.insert("login", login);

    QJsonDocument jsonDocument = QJsonDocument::fromVariant(json);
    if(jsonDocument.isNull() == true)
    {
        cout << "QJsonDocument::fromVariant(json) error";
        return;
    }

    QFile file(path);
    if(false == file.open(QIODevice::WriteOnly))
    {
        cout << "file open error";
        return;
    }

    file.write(jsonDocument.toJson());
    file.close();
}

void Common::writeLoginInfo(QString user, QString pwd, bool isRemeber, QString path)
{
    QString ip = getCfgValue("web_server", "ip");
    QString port = getCfgValue("web_server", "port");

    QMap<QString, QVariant> web_server;
    web_server.insert("ip", ip);
    web_server.insert("port", port);

    QMap<QString, QVariant> type_path;
    type_path.insert("path", m_typePath);

    //加密Base64
    QMap<QString, QVariant> login;
    login.insert("user", user.toUtf8().toBase64());
    login.insert("pwd", pwd.toUtf8().toBase64());
    login.insert("remember", isRemeber ? "yes" : "no");

    QMap<QString, QVariant> json;
    json.insert("web_server", web_server);
    json.insert("type_path", type_path);
    json.insert("login", login);

    QJsonDocument jsonDocument = QJsonDocument::fromVariant(json);
    if(jsonDocument.isNull() == true)
    {
        cout << "QJsonDocument::fromVariant(json) error";
        return;
    }

    QFile file(path);
    if(false == file.open(QIODevice::WriteOnly))
    {
        cout << "file open err";
        return;
    }

    file.write(jsonDocument.toJson());
    file.close();
}

QString Common::getFileMd5(QString filePath)
{
    QFile localFile(filePath);

    if(!localFile.open(QFile::ReadOnly))
    {
        cout << "file open err";
        return 0;
    }

    QCryptographicHash ch(QCryptographicHash::Md5);
    quint64 totalBytes = 0;
    quint64 bytesWritten = 0;
    quint64 bytesToWrite = 0;
    quint64 loadSize = 1024 * 4;
    QByteArray buf;

    totalBytes = localFile.size();
    bytesToWrite = totalBytes;

    while(1)
    {
        if(bytesToWrite > 0)
        {
            buf = localFile.read(qMin(bytesToWrite, loadSize));
            ch.addData(buf);
            bytesWritten += buf.length();
            bytesToWrite -= buf.length();
            buf.resize(0);
        }
        else break;

        if(bytesWritten == totalBytes)
        {
            break;
        }
    }

    localFile.close();
    QByteArray md5 = ch.result();
    return md5.toHex();
}

QString Common::getStrMd5(QString str)
{
    QByteArray arr;

    arr = QCryptographicHash::hash(str.toUtf8(), QCryptographicHash::Md5);

    return arr.toHex();
}

QString Common::getCode(QByteArray json)
{
    QJsonParseError err;

    QJsonDocument doc = QJsonDocument::fromJson(json, &err);
    if(err.error == QJsonParseError::NoError)
    {
        if(doc.isNull() || doc.isEmpty())
        {
            cout << "doc.isNULL() || doc.isEmpty()";
            return "";
        }

        if(doc.isObject())
        {
            QJsonObject obj = doc.object();
            return obj.value("code").toString();
        }
    }
    else
    {
        cout << "error = " << err.errorString();
    }
}

QString Common::getCfgValue(QString title, QString key, QString path)
{
    QFile file(path);

    if(false == file.open(QIODevice::ReadOnly))
    {
        cout << "file open failed";
        return "";
    }

    QByteArray json = file.readAll();
    file.close();

    QJsonParseError error;

    QJsonDocument doc = QJsonDocument::fromJson(json, &error);
    if(error.error ==QJsonParseError::NoError)
    {
        if(doc.isNull() || doc.isEmpty())
        {
            cout << "doc.isNULL() || doc.isEmpty()";
            return "";
        }

        if(doc.isObject())
        {
            QJsonObject obj = doc.object();

            QJsonObject tmp = obj.value(title).toObject();
            QStringList list = tmp.keys();
            for(int i = 0; i < list.size(); i++)
            {
                if(list.at(i) == key)
                {
                    return tmp.value(list.at(i)).toString();
                }
            }
        }
    }
    else
    {
        cout << "err = " << error.errorString();
    }
}

QString Common::getFileType(QString type)
{
    QString suffix = "suffix-" + type;

    if(true == m_typeList.contains(suffix))
    {
        return m_typePath + "/" + suffix;
    }

    return m_typePath + "/other.png";
}

void Common::writeRecord(QString user, QString name, QString code, QString path)
{
    QString fileName = path + user;
    QDir dir(path);
    if(!dir.exists())
    {
        if(dir.mkpath(path))
        {
            cout << path << "目录创建成功。。。";
        }
        else
        {
            cout << path << "目录创建成功。。。";
        }
    }
    cout << "fileName = " << fileName.toUtf8().data();
    QByteArray array;

    QFile file(fileName);

    if(true == file.exists())
    {
        if(false == file.open(QIODevice::ReadOnly))
        {
            cout << "file.open(QIODevice::ReadOnly) error!";
            return;
        }

        array = file.readAll();
        file.close();
    }

    if(false == file.open(QIODevice::WriteOnly))
    {
        cout << "file.open(QIODevice::WriteOnly) error!";
        return;
    }

    //获取当前时间
    QDateTime time = QDateTime::currentDateTime();
    QString timeStr = time.toString("yyyy-MM-dd hh:mm:ss ddd");

    /*
       秒传文件：
            文件已存在：{"code":"005"}
            秒传成功：  {"code":"006"}
            秒传失败：  {"code":"007"}
        上传文件：
            成功：{"code":"008"}
            失败：{"code":"009"}
        下载文件：
            成功：{"code":"010"}
            失败：{"code":"011"}
    */

    QString actionStr;
    if(code == "005")
    {
        actionStr = "上传失败，文件已存在";
    }
    else if(code == "006")
    {
        actionStr = "秒传成功";
    }
    else if(code == "008")
    {
        actionStr = "上传成功";
    }
    else if(code == "009")
    {
        actionStr = "上传失败";
    }
    else if(code == "010")
    {
        actionStr = "下载成功";
    }
    else if(code == "011")
    {
        actionStr = "下载失败";
    }

    QString str = QString("[%1]\t%2\t[%3]\r\n").arg(name).arg(timeStr).arg(actionStr);
    cout << str.toUtf8().data();

    file.write(str.toLocal8Bit());
    if(array.isEmpty() == false)
    {
        file.write(array);
    }

    file.close();
}

QString Common::getBoundary()
{
    qsrand(QTime(0, 0, 0).secsTo(QTime::currentTime()));
    QString tmp;

    for(int i = 0; i < 16; ++i)
    {
        tmp[i] = qrand() % (122-48) + 48;
    }

    return QString("------WebKitFormBoundary%1").arg(tmp);
}

void Common::getFileTypeList()
{
    QDir dir(m_typePath);
    if(!dir.exists())
    {
        dir.mkpath(m_typePath);
        cout << m_typePath << "创建成功！！！";
    }

    dir.setFilter(QDir::Files | QDir::NoDot | QDir::NoDotDot | QDir::NoSymLinks);
    dir.setSorting(QDir::Size | QDir::Reversed);

    QFileInfoList list = dir.entryInfoList();

    for(int i = 0; i < list.size(); ++i)
    {
        QFileInfo fileInfo = list.at(i);
        m_typeList.append(fileInfo.fileName());
    }
}
